home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / test / regrtest.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  32KB  |  902 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Regression test.
  5.  
  6. This will find all modules whose name is "test_*" in the test
  7. directory, and run them.  Various command line options provide
  8. additional facilities.
  9.  
  10. Command line options:
  11.  
  12. -v: verbose    -- run tests in verbose mode with output to stdout
  13. -w: verbose2   -- re-run failed tests in verbose mode
  14. -q: quiet      -- don\'t print anything except if a test fails
  15. -x: exclude    -- arguments are tests to *exclude*
  16. -s: single     -- run only a single test (see below)
  17. -S: slow       -- print the slowest 10 tests
  18. -r: random     -- randomize test execution order
  19. -f: fromfile   -- read names of tests to run from a file (see below)
  20. -l: findleaks  -- if GC is available detect tests that leak memory
  21. -u: use        -- specify which special resource intensive tests to run
  22. -h: help       -- print this text and exit
  23. -t: threshold  -- call gc.set_threshold(N)
  24. -T: coverage   -- turn on code coverage using the trace module
  25. -D: coverdir   -- Directory where coverage files are put
  26. -N: nocoverdir -- Put coverage files alongside modules
  27. -L: runleaks   -- run the leaks(1) command just before exit
  28. -R: huntrleaks -- search for reference leaks (needs debug build, v. slow)
  29. -M: memlimit   -- run very large memory-consuming tests
  30.  
  31. If non-option arguments are present, they are names for tests to run,
  32. unless -x is given, in which case they are names for tests not to run.
  33. If no test names are given, all tests are run.
  34.  
  35. -T turns on code coverage tracing with the trace module.
  36.  
  37. -D specifies the directory where coverage files are put.
  38.  
  39. -N Put coverage files alongside modules.
  40.  
  41. -s means to run only a single test and exit.  This is useful when
  42. doing memory analysis on the Python interpreter (which tend to consume
  43. too many resources to run the full regression test non-stop).  The
  44. file /tmp/pynexttest is read to find the next test to run.  If this
  45. file is missing, the first test_*.py file in testdir or on the command
  46. line is used.  (actually tempfile.gettempdir() is used instead of
  47. /tmp).
  48.  
  49. -f reads the names of tests from the file given as f\'s argument, one
  50. or more test names per line.  Whitespace is ignored.  Blank lines and
  51. lines beginning with \'#\' are ignored.  This is especially useful for
  52. whittling down failures involving interactions among tests.
  53.  
  54. -L causes the leaks(1) command to be run just before exit if it exists.
  55. leaks(1) is available on Mac OS X and presumably on some other
  56. FreeBSD-derived systems.
  57.  
  58. -R runs each test several times and examines sys.gettotalrefcount() to
  59. see if the test appears to be leaking references.  The argument should
  60. be of the form stab:run:fname where \'stab\' is the number of times the
  61. test is run to let gettotalrefcount settle down, \'run\' is the number
  62. of times further it is run and \'fname\' is the name of the file the
  63. reports are written to.  These parameters all have defaults (5, 4 and
  64. "reflog.txt" respectively), so the minimal invocation is \'-R ::\'.
  65.  
  66. -M runs tests that require an exorbitant amount of memory. These tests
  67. typically try to ascertain containers keep working when containing more than
  68. 2 billion objects, which only works on 64-bit systems. There are also some
  69. tests that try to exhaust the address space of the process, which only makes
  70. sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
  71. which is a string in the form of \'2.5Gb\', determines howmuch memory the
  72. tests will limit themselves to (but they may go slightly over.) The number
  73. shouldn\'t be more memory than the machine has (including swap memory). You
  74. should also keep in mind that swap memory is generally much, much slower
  75. than RAM, and setting memlimit to all available RAM or higher will heavily
  76. tax the machine. On the other hand, it is no use running these tests with a
  77. limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
  78. to use more than memlimit memory will be skipped. The big-memory tests
  79. generally run very, very long.
  80.  
  81. -u is used to specify which special resource intensive tests to run,
  82. such as those requiring large file support or network connectivity.
  83. The argument is a comma-separated list of words indicating the
  84. resources to test.  Currently only the following are defined:
  85.  
  86.     all -       Enable all special resources.
  87.  
  88.     audio -     Tests that use the audio device.  (There are known
  89.                 cases of broken audio drivers that can crash Python or
  90.                 even the Linux kernel.)
  91.  
  92.     curses -    Tests that use curses and will modify the terminal\'s
  93.                 state and output modes.
  94.  
  95.     lib2to3 -   Run the tests for 2to3 (They take a while.)
  96.  
  97.     largefile - It is okay to run some test that may create huge
  98.                 files.  These tests can take a long time and may
  99.                 consume >2GB of disk space temporarily.
  100.  
  101.     network -   It is okay to run tests that use external network
  102.                 resource, e.g. testing SSL support for sockets.
  103.  
  104.     bsddb -     It is okay to run the bsddb testsuite, which takes
  105.                 a long time to complete.
  106.  
  107.     decimal -   Test the decimal module against a large suite that
  108.                 verifies compliance with standards.
  109.  
  110.     compiler -  Test the compiler package by compiling all the source
  111.                 in the standard library and test suite.  This takes
  112.                 a long time.  Enabling this resource also allows
  113.                 test_tokenize to verify round-trip lexing on every
  114.                 file in the test library.
  115.  
  116.     subprocess  Run all tests for the subprocess module.
  117.  
  118.     urlfetch -  It is okay to download files required on testing.
  119.  
  120. To enable all resources except one, use \'-uall,-<resource>\'.  For
  121. example, to run all the tests except for the bsddb tests, give the
  122. option \'-uall,-bsddb\'.
  123. '''
  124. import cStringIO
  125. import getopt
  126. import os
  127. import random
  128. import re
  129. import sys
  130. import time
  131. import traceback
  132. import warnings
  133. warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '.*test.test_grammar$')
  134. if sys.maxint > 2147483647:
  135.     warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '<string>')
  136.  
  137. for mod in ('ctypes', 'gzip', 'zipfile', 'tarfile', 'encodings.zlib_codec', 'test.test_zipimport', 'test.test_zlib', 'test.test_zipfile', 'test.test_codecs', 'test.string_tests'):
  138.     warnings.filterwarnings(module = '.*%s$' % (mod,), action = 'ignore', category = ImportWarning)
  139.  
  140. if sys.platform == 'darwin':
  141.     
  142.     try:
  143.         import resource
  144.     except ImportError:
  145.         pass
  146.  
  147.     (soft, hard) = resource.getrlimit(resource.RLIMIT_STACK)
  148.     newsoft = min(hard, max(soft, 1024 * 2048))
  149.     resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  150.  
  151. from test import test_support
  152. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb', 'decimal', 'compiler', 'subprocess', 'urlfetch')
  153.  
  154. def usage(code, msg = ''):
  155.     print __doc__
  156.     if msg:
  157.         print msg
  158.     
  159.     sys.exit(code)
  160.  
  161.  
  162. def main(tests = None, testdir = None, verbose = 0, quiet = False, exclude = False, single = False, randomize = False, fromfile = None, findleaks = False, use_resources = None, trace = False, coverdir = 'coverage', runleaks = False, huntrleaks = False, verbose2 = False, print_slow = False):
  163.     """Execute a test suite.
  164.  
  165.     This also parses command-line options and modifies its behavior
  166.     accordingly.
  167.  
  168.     tests -- a list of strings containing test names (optional)
  169.     testdir -- the directory in which to look for tests (optional)
  170.  
  171.     Users other than the Python test suite will certainly want to
  172.     specify testdir; if it's omitted, the directory containing the
  173.     Python test suite is searched for.
  174.  
  175.     If the tests argument is omitted, the tests listed on the
  176.     command-line will be used.  If that's empty, too, then all *.py
  177.     files beginning with test_ will be used.
  178.  
  179.     The other default arguments (verbose, quiet, exclude,
  180.     single, randomize, findleaks, use_resources, trace, coverdir, and
  181.     print_slow) allow programmers calling main() directly to set the
  182.     values that would normally be set by flags on the command line.
  183.     """
  184.     test_support.record_original_stdout(sys.stdout)
  185.     
  186.     try:
  187.         (opts, args) = getopt.getopt(sys.argv[1:], 'hvgqxsSrf:lu:t:TD:NLR:wM:', [
  188.             'help',
  189.             'verbose',
  190.             'quiet',
  191.             'exclude',
  192.             'single',
  193.             'slow',
  194.             'random',
  195.             'fromfile',
  196.             'findleaks',
  197.             'use=',
  198.             'threshold=',
  199.             'trace',
  200.             'coverdir=',
  201.             'nocoverdir',
  202.             'runleaks',
  203.             'huntrleaks=',
  204.             'verbose2',
  205.             'memlimit='])
  206.     except getopt.error:
  207.         msg = None
  208.         usage(2, msg)
  209.  
  210.     if use_resources is None:
  211.         use_resources = []
  212.     
  213.     for o, a in opts:
  214.         if o in ('-h', '--help'):
  215.             usage(0)
  216.             continue
  217.         if o in ('-v', '--verbose'):
  218.             verbose += 1
  219.             continue
  220.         if o in ('-w', '--verbose2'):
  221.             verbose2 = True
  222.             continue
  223.         if o in ('-q', '--quiet'):
  224.             quiet = True
  225.             verbose = 0
  226.             continue
  227.         if o in ('-x', '--exclude'):
  228.             exclude = True
  229.             continue
  230.         if o in ('-s', '--single'):
  231.             single = True
  232.             continue
  233.         if o in ('-S', '--slow'):
  234.             print_slow = True
  235.             continue
  236.         if o in ('-r', '--randomize'):
  237.             randomize = True
  238.             continue
  239.         if o in ('-f', '--fromfile'):
  240.             fromfile = a
  241.             continue
  242.         if o in ('-l', '--findleaks'):
  243.             findleaks = True
  244.             continue
  245.         if o in ('-L', '--runleaks'):
  246.             runleaks = True
  247.             continue
  248.         if o in ('-t', '--threshold'):
  249.             import gc as gc
  250.             gc.set_threshold(int(a))
  251.             continue
  252.         if o in ('-T', '--coverage'):
  253.             trace = True
  254.             continue
  255.         if o in ('-D', '--coverdir'):
  256.             coverdir = os.path.join(os.getcwd(), a)
  257.             continue
  258.         None if o in ('-N', '--nocoverdir') else len(huntrleaks[2]) == 0
  259.         if o in ('-M', '--memlimit'):
  260.             test_support.set_memlimit(a)
  261.             continue
  262.         if o in ('-u', '--use'):
  263.             u = [ x.lower() for x in a.split(',') ]
  264.             for r in u:
  265.                 remove = False
  266.                 if r[0] == '-':
  267.                     remove = True
  268.                     r = r[1:]
  269.                 
  270.                 if r not in RESOURCE_NAMES:
  271.                     usage(1, 'Invalid -u/--use option: ' + a)
  272.                 
  273.                 if remove:
  274.                     if r in use_resources:
  275.                         use_resources.remove(r)
  276.                     
  277.                 r in use_resources
  278.                 if r not in use_resources:
  279.                     use_resources.append(r)
  280.                     continue
  281.             
  282.     
  283.     if single and fromfile:
  284.         usage(2, "-s and -f don't go together!")
  285.     
  286.     good = []
  287.     bad = []
  288.     skipped = []
  289.     resource_denieds = []
  290.     if findleaks:
  291.         
  292.         try:
  293.             import gc as gc
  294.         except ImportError:
  295.             print 'No GC available, disabling findleaks.'
  296.             findleaks = False
  297.  
  298.         found_garbage = []
  299.     
  300.     if single:
  301.         gettempdir = gettempdir
  302.         import tempfile
  303.         filename = os.path.join(gettempdir(), 'pynexttest')
  304.         
  305.         try:
  306.             fp = open(filename, 'r')
  307.             next = fp.read().strip()
  308.             tests = [
  309.                 next]
  310.             fp.close()
  311.         except IOError:
  312.             pass
  313.         except:
  314.             None<EXCEPTION MATCH>IOError
  315.         
  316.  
  317.     None<EXCEPTION MATCH>IOError
  318.     if fromfile:
  319.         tests = []
  320.         fp = open(fromfile)
  321.         for line in fp:
  322.             guts = line.split()
  323.             if guts and not guts[0].startswith('#'):
  324.                 tests.extend(guts)
  325.                 continue
  326.         
  327.         fp.close()
  328.     
  329.     if args:
  330.         args = map(removepy, args)
  331.     
  332.     if tests:
  333.         tests = map(removepy, tests)
  334.     
  335.     stdtests = STDTESTS[:]
  336.     nottests = NOTTESTS[:]
  337.     if exclude:
  338.         for arg in args:
  339.             if arg in stdtests:
  340.                 stdtests.remove(arg)
  341.                 continue
  342.         
  343.         nottests[:0] = args
  344.         args = []
  345.     
  346.     if not tests and args:
  347.         pass
  348.     tests = findtests(testdir, stdtests, nottests)
  349.     if single:
  350.         tests = tests[:1]
  351.     
  352.     if randomize:
  353.         random.shuffle(tests)
  354.     
  355.     if trace:
  356.         import trace
  357.         tracer = trace.Trace(ignoredirs = [
  358.             sys.prefix,
  359.             sys.exec_prefix], trace = False, count = True)
  360.     
  361.     test_times = []
  362.     test_support.verbose = verbose
  363.     test_support.use_resources = use_resources
  364.     save_modules = sys.modules.keys()
  365.     for test in tests:
  366.         if not quiet:
  367.             print test
  368.             sys.stdout.flush()
  369.         
  370.         if trace:
  371.             tracer.runctx('runtest(test, verbose, quiet,        test_times, testdir)', globals = globals(), locals = vars())
  372.         else:
  373.             
  374.             try:
  375.                 ok = runtest(test, verbose, quiet, test_times, testdir, huntrleaks)
  376.             except KeyboardInterrupt:
  377.                 print 
  378.                 break
  379.             except:
  380.                 raise 
  381.  
  382.             if ok > 0:
  383.                 good.append(test)
  384.             elif ok == 0:
  385.                 bad.append(test)
  386.             else:
  387.                 skipped.append(test)
  388.                 if ok == -2:
  389.                     resource_denieds.append(test)
  390.                 
  391.         if findleaks:
  392.             gc.collect()
  393.             if gc.garbage:
  394.                 print 'Warning: test created', len(gc.garbage), 'uncollectable object(s).'
  395.                 found_garbage.extend(gc.garbage)
  396.                 del gc.garbage[:]
  397.             
  398.         
  399.         for module in sys.modules.keys():
  400.             if module not in save_modules and module.startswith('test.'):
  401.                 test_support.unload(module)
  402.                 continue
  403.         
  404.     
  405.     good.sort()
  406.     bad.sort()
  407.     skipped.sort()
  408.     if good and not quiet:
  409.         if not bad and not skipped and len(good) > 1:
  410.             print 'All',
  411.         
  412.         print count(len(good), 'test'), 'OK.'
  413.     
  414.     if print_slow:
  415.         test_times.sort(reverse = True)
  416.         print '10 slowest tests:'
  417.         for time, test in test_times[:10]:
  418.             print '%s: %.1fs' % (test, time)
  419.         
  420.     
  421.     if bad:
  422.         print count(len(bad), 'test'), 'failed:'
  423.         printlist(bad)
  424.     
  425.     if skipped and not quiet:
  426.         print count(len(skipped), 'test'), 'skipped:'
  427.         printlist(skipped)
  428.         e = _ExpectedSkips()
  429.         plat = sys.platform
  430.         if e.isvalid():
  431.             surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  432.             if surprise:
  433.                 print count(len(surprise), 'skip'), 'unexpected on', plat + ':'
  434.                 printlist(surprise)
  435.             else:
  436.                 print 'Those skips are all expected on', plat + '.'
  437.         else:
  438.             print 'Ask someone to teach regrtest.py about which tests are'
  439.             print 'expected to get skipped on', plat + '.'
  440.     
  441.     if verbose2 and bad:
  442.         print 'Re-running failed tests in verbose mode'
  443.         for test in bad:
  444.             print 'Re-running test %r in verbose mode' % test
  445.             sys.stdout.flush()
  446.             
  447.             try:
  448.                 test_support.verbose = True
  449.                 ok = runtest(test, True, quiet, test_times, testdir, huntrleaks)
  450.             continue
  451.             except KeyboardInterrupt:
  452.                 print 
  453.                 break
  454.                 continue
  455.                 raise 
  456.                 continue
  457.             
  458.  
  459.         
  460.     
  461.     if single:
  462.         alltests = findtests(testdir, stdtests, nottests)
  463.         for i in range(len(alltests)):
  464.             if tests[0] == alltests[i]:
  465.                 if i == len(alltests) - 1:
  466.                     os.unlink(filename)
  467.                 else:
  468.                     fp = open(filename, 'w')
  469.                     fp.write(alltests[i + 1] + '\n')
  470.                     fp.close()
  471.                 break
  472.                 continue
  473.         
  474.     
  475.     if trace:
  476.         r = tracer.results()
  477.         r.write_results(show_missing = True, summary = True, coverdir = coverdir)
  478.     
  479.     if runleaks:
  480.         os.system('leaks %d' % os.getpid())
  481.     
  482.     sys.exit(len(bad) > 0)
  483.  
  484. STDTESTS = [
  485.     'test_grammar',
  486.     'test_opcodes',
  487.     'test_dict',
  488.     'test_builtin',
  489.     'test_exceptions',
  490.     'test_types',
  491.     'test_unittest',
  492.     'test_doctest',
  493.     'test_doctest2']
  494. NOTTESTS = [
  495.     'test_support',
  496.     'test_future1',
  497.     'test_future2']
  498.  
  499. def findtests(testdir = None, stdtests = STDTESTS, nottests = NOTTESTS):
  500.     '''Return a list of all applicable test modules.'''
  501.     if not testdir:
  502.         testdir = findtestdir()
  503.     
  504.     names = os.listdir(testdir)
  505.     tests = []
  506.     for name in names:
  507.         if name[:5] == 'test_' and name[-3:] == os.extsep + 'py':
  508.             modname = name[:-3]
  509.             if modname not in stdtests and modname not in nottests:
  510.                 tests.append(modname)
  511.             
  512.         modname not in nottests
  513.     
  514.     tests.sort()
  515.     return stdtests + tests
  516.  
  517.  
  518. def runtest(test, verbose, quiet, test_times, testdir = None, huntrleaks = False):
  519.     """Run a single test.
  520.  
  521.     test -- the name of the test
  522.     verbose -- if true, print more messages
  523.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  524.     test_times -- a list of (time, test_name) pairs
  525.     testdir -- test directory
  526.     huntrleaks -- run multiple times to test for leaks; requires a debug
  527.                   build; a triple corresponding to -R's three arguments
  528.     Return:
  529.         -2  test skipped because resource denied
  530.         -1  test skipped for some other reason
  531.          0  test failed
  532.          1  test passed
  533.     """
  534.     
  535.     try:
  536.         return runtest_inner(test, verbose, quiet, test_times, testdir, huntrleaks)
  537.     finally:
  538.         cleanup_test_droppings(test, verbose)
  539.  
  540.  
  541.  
  542. def runtest_inner(test, verbose, quiet, test_times, testdir = None, huntrleaks = False):
  543.     test_support.unload(test)
  544.     if not testdir:
  545.         testdir = findtestdir()
  546.     
  547.     if verbose:
  548.         capture_stdout = None
  549.     else:
  550.         capture_stdout = cStringIO.StringIO()
  551.     
  552.     try:
  553.         save_stdout = sys.stdout
  554.         
  555.         try:
  556.             if capture_stdout:
  557.                 sys.stdout = capture_stdout
  558.             
  559.             if test.startswith('test.'):
  560.                 abstest = test
  561.             else:
  562.                 abstest = 'test.' + test
  563.             start_time = time.time()
  564.             the_package = __import__(abstest, globals(), locals(), [])
  565.             the_module = getattr(the_package, test)
  566.             indirect_test = getattr(the_module, 'test_main', None)
  567.             if indirect_test is not None:
  568.                 indirect_test()
  569.             
  570.             if huntrleaks:
  571.                 dash_R(the_module, test, indirect_test, huntrleaks)
  572.             
  573.             test_time = time.time() - start_time
  574.             test_times.append((test_time, test))
  575.         finally:
  576.             sys.stdout = save_stdout
  577.  
  578.     except test_support.ResourceDenied:
  579.         msg = None
  580.         if not quiet:
  581.             print test, 'skipped --', msg
  582.             sys.stdout.flush()
  583.         
  584.         return -2
  585.         except (ImportError, test_support.TestSkipped):
  586.             msg = None
  587.             if not quiet:
  588.                 print test, 'skipped --', msg
  589.                 sys.stdout.flush()
  590.             
  591.             return -1
  592.             except KeyboardInterrupt:
  593.                 raise 
  594.             except test_support.TestFailed:
  595.                 msg = None
  596.                 print 'test', test, 'failed --', msg
  597.                 sys.stdout.flush()
  598.                 return 0
  599.                 (type, value) = sys.exc_info()[:2]
  600.                 print 'test', test, 'crashed --', str(type) + ':', value
  601.                 sys.stdout.flush()
  602.                 if verbose:
  603.                     traceback.print_exc(file = sys.stdout)
  604.                     sys.stdout.flush()
  605.                 
  606.     return 0
  607.  
  608.     if verbose or huntrleaks:
  609.         return 1
  610.     output = capture_stdout.getvalue()
  611.     if not output:
  612.         return 1
  613.     print 'test', test, 'produced unexpected output:'
  614.     print '*' * 70
  615.     print output
  616.     print '*' * 70
  617.     sys.stdout.flush()
  618.     return 0
  619.  
  620.  
  621. def cleanup_test_droppings(testname, verbose):
  622.     import shutil as shutil
  623.     for name in (test_support.TESTFN, 'db_home'):
  624.         if not os.path.exists(name):
  625.             continue
  626.         
  627.         if os.path.isdir(name):
  628.             kind = 'directory'
  629.             nuker = shutil.rmtree
  630.         elif os.path.isfile(name):
  631.             kind = 'file'
  632.             nuker = os.unlink
  633.         else:
  634.             raise SystemError('os.path says %r exists but is neither directory nor file' % name)
  635.         if os.path.isdir(name):
  636.             print '%r left behind %s %r' % (testname, kind, name)
  637.         
  638.         
  639.         try:
  640.             nuker(name)
  641.         continue
  642.         except Exception:
  643.             msg = None
  644.             print >>sys.stderr, "%r left behind %s %r and it couldn't be removed: %s" % (testname, kind, name, msg)
  645.             continue
  646.         
  647.  
  648.     
  649.  
  650.  
  651. def dash_R(the_module, test, indirect_test, huntrleaks):
  652.     import copy_reg as copy_reg
  653.     import _abcoll as _abcoll
  654.     import io as io
  655.     if not hasattr(sys, 'gettotalrefcount'):
  656.         raise Exception('Tracking reference leaks requires a debug build of Python')
  657.     hasattr(sys, 'gettotalrefcount')
  658.     fs = warnings.filters[:]
  659.     ps = copy_reg.dispatch_table.copy()
  660.     pic = sys.path_importer_cache.copy()
  661.     abcs = { }
  662.     modules = (_abcoll, io)
  663.     for mod in modules:
  664.         pass
  665.     
  666.     deltas = []
  667.     (nwarmup, ntracked, fname) = huntrleaks
  668.     repcount = nwarmup + ntracked
  669.     print >>sys.stderr, 'beginning', repcount, 'repetitions'
  670.     print >>sys.stderr, '1234567890' * (repcount // 10 + 1)[:repcount]
  671.     dash_R_cleanup(fs, ps, pic, abcs)
  672.     for i in range(repcount):
  673.         rc = sys.gettotalrefcount()
  674.         run_the_test()
  675.         sys.stderr.write('.')
  676.         dash_R_cleanup(fs, ps, pic, abcs)
  677.         if i >= nwarmup:
  678.             deltas.append(sys.gettotalrefcount() - rc - 2)
  679.             continue
  680.     
  681.     print >>sys.stderr
  682.     if any(deltas):
  683.         msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas))
  684.         print >>sys.stderr, msg
  685.         refrep = open(fname, 'a')
  686.         print >>refrep, msg
  687.         refrep.close()
  688.     
  689.  
  690.  
  691. def dash_R_cleanup(fs, ps, pic, abcs):
  692.     import gc
  693.     import copy_reg
  694.     import _strptime as _strptime
  695.     import linecache as linecache
  696.     dircache = test_support.import_module('dircache', deprecated = True)
  697.     import urlparse as urlparse
  698.     import urllib as urllib
  699.     import urllib2 as urllib2
  700.     import mimetypes as mimetypes
  701.     import doctest as doctest
  702.     import struct as struct
  703.     import filecmp as filecmp
  704.     _path_created = _path_created
  705.     import distutils.dir_util
  706.     for mod in sys.modules.values():
  707.         if hasattr(mod, '__warningregistry__'):
  708.             del mod.__warningregistry__
  709.             continue
  710.     
  711.     warnings.filters[:] = fs
  712.     copy_reg.dispatch_table.clear()
  713.     copy_reg.dispatch_table.update(ps)
  714.     sys.path_importer_cache.clear()
  715.     sys.path_importer_cache.update(pic)
  716.     sys._clear_type_cache()
  717.     for abc, registry in abcs.items():
  718.         abc._abc_registry = registry.copy()
  719.         abc._abc_cache.clear()
  720.         abc._abc_negative_cache.clear()
  721.     
  722.     _path_created.clear()
  723.     re.purge()
  724.     _strptime._regex_cache.clear()
  725.     urlparse.clear_cache()
  726.     urllib.urlcleanup()
  727.     urllib2.install_opener(None)
  728.     dircache.reset()
  729.     linecache.clearcache()
  730.     mimetypes._default_mime_types()
  731.     filecmp._cache.clear()
  732.     struct._clearcache()
  733.     doctest.master = None
  734.     gc.collect()
  735.  
  736.  
  737. def findtestdir():
  738.     if __name__ == '__main__':
  739.         file = sys.argv[0]
  740.     else:
  741.         file = __file__
  742.     if not os.path.dirname(file):
  743.         pass
  744.     testdir = os.curdir
  745.     return testdir
  746.  
  747.  
  748. def removepy(name):
  749.     if name.endswith(os.extsep + 'py'):
  750.         name = name[:-3]
  751.     
  752.     return name
  753.  
  754.  
  755. def count(n, word):
  756.     if n == 1:
  757.         return '%d %s' % (n, word)
  758.     return '%d %ss' % (n, word)
  759.  
  760.  
  761. def printlist(x, width = 70, indent = 4):
  762.     '''Print the elements of iterable x to stdout.
  763.  
  764.     Optional arg width (default 70) is the maximum line length.
  765.     Optional arg indent (default 4) is the number of blanks with which to
  766.     begin each line.
  767.     '''
  768.     fill = fill
  769.     import textwrap
  770.     blanks = ' ' * indent
  771.     print fill(' '.join(map(str, x)), width, initial_indent = blanks, subsequent_indent = blanks)
  772.  
  773. _expectations = {
  774.     'win32': '\n        test__locale\n        test_bsddb185\n        test_bsddb3\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_epoll\n        test_gdbm\n        test_grp\n        test_ioctl\n        test_largefile\n        test_kqueue\n        test_mhlib\n        test_openpty\n        test_ossaudiodev\n        test_pipes\n        test_poll\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_threadsignals\n        test_timing\n        test_wait3\n        test_wait4\n        ',
  775.     'linux2': '\n        test_bsddb185\n        test_curses\n        test_dl\n        test_largefile\n        test_kqueue\n        test_ossaudiodev\n        ',
  776.     'mac': '\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_epoll\n        test_grp\n        test_ioctl\n        test_largefile\n        test_locale\n        test_kqueue\n        test_mmap\n        test_openpty\n        test_ossaudiodev\n        test_poll\n        test_popen\n        test_popen2\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_sundry\n        test_tarfile\n        test_timing\n        ',
  777.     'unixware7': '\n        test_bsddb\n        test_bsddb185\n        test_dl\n        test_epoll\n        test_largefile\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sundry\n        ',
  778.     'openunix8': '\n        test_bsddb\n        test_bsddb185\n        test_dl\n        test_epoll\n        test_largefile\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sundry\n        ',
  779.     'sco_sv3': '\n        test_asynchat\n        test_bsddb\n        test_bsddb185\n        test_dl\n        test_fork1\n        test_epoll\n        test_gettext\n        test_largefile\n        test_locale\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_queue\n        test_sax\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        ',
  780.     'riscos': '\n        test_asynchat\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_commands\n        test_crypt\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_epoll\n        test_gdbm\n        test_grp\n        test_largefile\n        test_locale\n        test_kqueue\n        test_mmap\n        test_openpty\n        test_poll\n        test_popen2\n        test_pty\n        test_pwd\n        test_strop\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        test_timing\n        ',
  781.     'darwin': '\n        test__locale\n        test_bsddb\n        test_bsddb3\n        test_curses\n        test_epoll\n        test_gdbm\n        test_largefile\n        test_locale\n        test_kqueue\n        test_minidom\n        test_ossaudiodev\n        test_poll\n        ',
  782.     'sunos5': '\n        test_bsddb\n        test_bsddb185\n        test_curses\n        test_dbm\n        test_epoll\n        test_kqueue\n        test_gdbm\n        test_gzip\n        test_openpty\n        test_zipfile\n        test_zlib\n        ',
  783.     'hp-ux11': '\n        test_bsddb\n        test_bsddb185\n        test_curses\n        test_dl\n        test_epoll\n        test_gdbm\n        test_gzip\n        test_largefile\n        test_locale\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_zipfile\n        test_zlib\n        ',
  784.     'atheos': '\n        test_bsddb185\n        test_curses\n        test_dl\n        test_gdbm\n        test_epoll\n        test_largefile\n        test_locale\n        test_kqueue\n        test_mhlib\n        test_mmap\n        test_poll\n        test_popen2\n        test_resource\n        ',
  785.     'cygwin': '\n        test_bsddb185\n        test_bsddb3\n        test_curses\n        test_dbm\n        test_epoll\n        test_ioctl\n        test_kqueue\n        test_largefile\n        test_locale\n        test_ossaudiodev\n        test_socketserver\n        ',
  786.     'os2emx': '\n        test_audioop\n        test_bsddb185\n        test_bsddb3\n        test_commands\n        test_curses\n        test_dl\n        test_epoll\n        test_kqueue\n        test_largefile\n        test_mhlib\n        test_mmap\n        test_openpty\n        test_ossaudiodev\n        test_pty\n        test_resource\n        test_signal\n        ',
  787.     'freebsd4': '\n        test_bsddb\n        test_bsddb3\n        test_epoll\n        test_gdbm\n        test_locale\n        test_ossaudiodev\n        test_pep277\n        test_pty\n        test_socket_ssl\n        test_socketserver\n        test_tcl\n        test_timeout\n        test_urllibnet\n        test_multiprocessing\n        ',
  788.     'aix5': '\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_dl\n        test_epoll\n        test_gdbm\n        test_gzip\n        test_kqueue\n        test_ossaudiodev\n        test_tcl\n        test_zipimport\n        test_zlib\n        ',
  789.     'openbsd3': '\n        test_bsddb\n        test_bsddb3\n        test_ctypes\n        test_dl\n        test_epoll\n        test_gdbm\n        test_locale\n        test_normalization\n        test_ossaudiodev\n        test_pep277\n        test_tcl\n        test_multiprocessing\n        ',
  790.     'netbsd3': '\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_ctypes\n        test_curses\n        test_dl\n        test_epoll\n        test_gdbm\n        test_locale\n        test_ossaudiodev\n        test_pep277\n        test_tcl\n        test_multiprocessing\n        ' }
  791. _expectations['freebsd5'] = _expectations['freebsd4']
  792. _expectations['freebsd6'] = _expectations['freebsd4']
  793. _expectations['freebsd7'] = _expectations['freebsd4']
  794. _expectations['freebsd8'] = _expectations['freebsd4']
  795.  
  796. class _ExpectedSkips:
  797.     
  798.     def __init__(self):
  799.         import os.path as os
  800.         test_timeout = test_timeout
  801.         import test
  802.         self.valid = False
  803.         if sys.platform in _expectations:
  804.             s = _expectations[sys.platform]
  805.             self.expected = set(s.split())
  806.             self.expected.add('test_linuxaudiodev')
  807.             if not os.path.supports_unicode_filenames:
  808.                 self.expected.add('test_pep277')
  809.             
  810.             
  811.             try:
  812.                 test_socket_ssl = test_socket_ssl
  813.                 import test
  814.             except ImportError:
  815.                 pass
  816.  
  817.             if test_socket_ssl.skip_expected:
  818.                 self.expected.add('test_socket_ssl')
  819.             
  820.             if test_timeout.skip_expected:
  821.                 self.expected.add('test_timeout')
  822.             
  823.             if sys.maxint == 0x7FFFFFFFFFFFFFFFL:
  824.                 self.expected.add('test_imageop')
  825.             
  826.             if sys.platform not in ('mac', 'darwin'):
  827.                 MAC_ONLY = [
  828.                     'test_macos',
  829.                     'test_macostools',
  830.                     'test_aepack',
  831.                     'test_plistlib',
  832.                     'test_scriptpackages',
  833.                     'test_applesingle']
  834.                 for skip in MAC_ONLY:
  835.                     self.expected.add(skip)
  836.                 
  837.             elif len(u'\x00'.encode('unicode-internal')) == 4:
  838.                 self.expected.add('test_macostools')
  839.             
  840.             if sys.platform != 'win32':
  841.                 WIN_ONLY = [
  842.                     'test_unicode_file',
  843.                     'test_winreg',
  844.                     'test_winsound',
  845.                     'test_startfile',
  846.                     'test_sqlite']
  847.                 for skip in WIN_ONLY:
  848.                     self.expected.add(skip)
  849.                 
  850.             
  851.             if sys.platform != 'irix':
  852.                 IRIX_ONLY = [
  853.                     'test_imageop',
  854.                     'test_al',
  855.                     'test_cd',
  856.                     'test_cl',
  857.                     'test_gl',
  858.                     'test_imgfile']
  859.                 for skip in IRIX_ONLY:
  860.                     self.expected.add(skip)
  861.                 
  862.             
  863.             if sys.platform != 'sunos5':
  864.                 self.expected.add('test_sunaudiodev')
  865.                 self.expected.add('test_nis')
  866.             
  867.             if not sys.py3kwarning:
  868.                 self.expected.add('test_py3kwarn')
  869.             
  870.             self.valid = True
  871.         
  872.  
  873.     
  874.     def isvalid(self):
  875.         '''Return true iff _ExpectedSkips knows about the current platform.'''
  876.         return self.valid
  877.  
  878.     
  879.     def getexpected(self):
  880.         '''Return set of test names we expect to skip on current platform.
  881.  
  882.         self.isvalid() must be true.
  883.         '''
  884.         if not self.isvalid():
  885.             raise AssertionError
  886.         return self.expected
  887.  
  888.  
  889. if __name__ == '__main__':
  890.     mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
  891.     i = pathlen = len(sys.path)
  892.     while i >= 0:
  893.         i -= 1
  894.         if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
  895.             del sys.path[i]
  896.         
  897.     if len(sys.path) == pathlen:
  898.         print 'Could not find %r in sys.path to remove it' % mydir
  899.     
  900.     main()
  901.  
  902.